<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\AdminAttachment;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use zgldh\QiniuStorage\QiniuStorage;

class AdminAttachmentController extends AdminController
{
    use HasUploadedFile;

    /**
     * 自定义文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed|void
     */
    public function upload(string $disk="qiniu") {
        $request=request();
        $storage = Storage::disk($disk);
        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            // 删除文件并响应
            return $this->deleteFileAndResponse($storage);
        }
        if ($request->file('file')) {
            $file = $request->file;
        } else {
            $file = $request->_file_;
        }
        if (empty($file)) {
            return $this->responseErrorMessage('未检测到文件');
        }
        //$md5 = md5_file($file->path());//大文件消耗性能
        $md5 = md5(unique_no("FILES_", time()));
        //暂时取消 同一文件不覆盖
        $exist = \App\Models\AdminAttachment::where("md5", $md5)->first();
        if (!empty($exist)) {
            //  return $this->responseUploaded($exist->url,$exist->url);
        }
        // 获取上传的字段名称
        $arr=explode('.',$file->getClientOriginalName());
        $ext=$arr[count($arr)-1];
        $allows =  [//限制文件类型 ,
            "image" => ['jpg', 'jpeg', 'png', 'bmp', 'svg', "ico", 'gif', 'webp'],
            "doc" => ['pdf', "doc", 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'cvs', 'wps', 'txt', 'md', 'rtf'],
            "video" => ['mp4', 'api', 'flv', 'mpg', 'mpeg', 'wmv', '3gp', 'rmvb', 'rm'],
            "audio" => ['mp3', 'wmv', 'amr', 'aud'],
            "file" => ['zip', 'rar', '7z','apk','ipa'],
        ];
        $dir = "";

        foreach ($allows as $key => $val) {
            if (in_array($ext, $val)) {
                $dir = $key;
            }
        }
        if ($dir === "" && isset($allows) &&!empty($allows)) {
            return $this->responseErrorMessage("不允许上传的文件类型！");
        }else if ($dir === "") {
            $dir = "file";
        }
        $path="uploads/" . $dir."s/".date("Ym");
        $newName =  $md5 . "." . $ext;
        $size=$file->getSize()/1024;
        if($size>(5*1024)&&$dir=='image'){//大于5M, 压缩

            //获取上传图片
            $score_file = $file;
            //str_random
            $ext = $score_file->getClientOriginalExtension();
            //src/Illuminate/Support/Str.php
            $upload_file_name = $md5 . '.' . $ext;
            //图片压缩上传
            $image = Image::make($file);
            $width = $image->getWidth();
            // 尺寸等比压缩，最大宽度800

            if ($width> 4000) {
                // 等比缩放，需要计算宽度缩放的比例，再计算出缩放后的图片高度
                $proportion = $width / 4000;
                $height = ceil($image->getHeight() / $proportion);
                $image = $image->resize(4000, $height);
                $image->save(storage_path('/app/public') .'/'. $upload_file_name, 86);
                $content=file_get_contents(storage_path('/app/public') .'/'. $upload_file_name);
            }else  if ($width> 3000) {
                // 等比缩放，需要计算宽度缩放的比例，再计算出缩放后的图片高度
                $proportion = $width / 3000;
                $height = ceil($image->getHeight() / $proportion);
                $image = $image->resize(3000, $height);
                $image->save(storage_path('/app/public') .'/'. $upload_file_name, 94);
                $content=file_get_contents(storage_path('/app/public') .'/'. $upload_file_name);
            }else  if ($width> 2000) {
                // 等比缩放，需要计算宽度缩放的比例，再计算出缩放后的图片高度
                $proportion = $width / 2000;
                $height = ceil($image->getHeight() / $proportion);
                $image = $image->resize(2000, $height);
                $image->save(storage_path('/app/public') .'/'. $upload_file_name, 98);
                $content=file_get_contents(storage_path('/app/public') .'/'. $upload_file_name);
            }else{
                $content = (string) Image::make($file)->encode('jpg',100);    //这里必需写jpg  才能压缩，   后面的参数  1-100  是图片质量
                file_put_contents(storage_path('/app/public') .'/'. $upload_file_name,$content);
            }

            $qiniu=QiniuStorage::disk('qiniu');
            $result=$qiniu->put($path.'/'.$newName,$content);
            if($result)$result=$path.'/'.$newName;
            $size=filesize(storage_path('/app/public') .'/'. $upload_file_name)/1024;
            unlink(storage_path('/app/public') .'/'. $upload_file_name);
        }else{
            $result = $file->storeAs($path,  $newName,$disk);
        }
        $url=$storage->url($result);
        $url=str_ireplace("http://","https://",$url);
        try {
            if ($result) {
                \App\Models\AdminAttachment::insert([
                    'platform' =>1,
                    'path' => $path.$newName,
                    'type' => $dir,
                    'url' => $url,
                    'md5' => $md5,
                    'platform'=>0,
                    'size'=>$file->getSize()/1024,
                    'disk' => $disk,
                    'ext'=>$ext,
                    'created_at' => date("Y-m-d H:i:s"),
                    'updated_at' => date("Y-m-d H:i:s"),
                ]);
            }

            return $result
                ? $this->responseUploaded($url,$url )
                : $this->responseErrorMessage('文件上传失败');
        } catch (\Excetion $e) {
            $this->responseErrorMessage('文件上传失败, ' . $e->getMessage());
        }

    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AdminAttachment(), function (Grid $grid) {
            $grid->quickSearch('url');
            $grid->model()->orderByDesc('id');
            $grid->column('id')->sortable();
            $grid->column('disk');
            $grid->column('url')->copyable()->display(function(){
                return "<a class='grid-column-copyable text-muted' href='javascript:void(0);' data-content='".$this->url."'  data-placement='bottom'><i class='fa fa-copy'></i>&nbsp;点击复制</a>";
            });
            $grid->column('urlx','预览')->display(function(){
                if($this->type=='image'){
                    return "<img src='".$this->url."' data-action='preview-img' style='max-width:50px;max-height:50px;cursor:pointer' class='img img-thumbnail'/>";
                }else{
                    return "<a href='".$this->url."'>新窗口打开</a>";
                }
            });
            $grid->column('size')->sortable();
            $grid->column('type');
            $grid->column('platform');
            $grid->column('created_at')->filter(Grid\Column\Filter\Like::make()->date());
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('url');
                $filter->between('size');
                $filter->between('created_at')->datetime();
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AdminAttachment(), function (Show $show) {
            $show->field('id');
            $show->field('driver');
            $show->field('path');
            $show->field('url');
            $show->field('size');
            $show->field('type');
            $show->field('ext');
            $show->field('md5');
            $show->field('platform');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminAttachment(), function (Form $form) {
            $form->display('id');
            $form->file('file')->url('upload')->maxSize(1024*25);
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
